<?php

namespace app\service;

use app\common\BaseService;
use app\model\User as UserModel;
use think\facade\Db;

class UserService extends BaseService {
  public static function getInstance(): UserService {
    return parent::getInstance();
  }

  public static function getModel(): UserModel {
    return UserModel::getInstance();
  }

  public static function getUserByName($username){
    $res = self::getModel()
      ->where('username', '=', $username)
      ->find();
    if ($res) {
      return $res->toArray();
    } else {
      return [];
    }
  }

  public static function updateUser($id, $update) {
    return self::getModel()
      ->where('id', $id)
      ->update($update);
  }

  public function storeAll() {
    return Db::table('user')
      ->field('base, basename')
      ->where('groupid', '=', 8)
      ->group('base,basename')
      ->select()
      ->toArray();
  }

  /*
   * 通过condition获取HouseOut
   */
  public function getUserByCondition($conditions, $order = ['id' => 'desc']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }

  /**
   * 保存用户修改（运营账号）
   */
  public function updateMultiUser($data) {
    $updateUser = [];
    foreach ($data as $value) {
      if (!$value['id']) {
        return ['status' => false, 'msg' => '用户ID不能为空'];
      }
      if (!$value['username']) {
        return ['status' => false, 'msg' => '账户名不能为空'];
      }
      $operateStore = isset($value['operate_store']) && $value['operate_store'] ? join(',', $value['operate_store']) : '';
      $updateUser[] = [
        'id' => $value['id'],
        'username' => $value['username'],
        'operate_store' => $operateStore
      ];
    }
    $res = self::getModel()->saveAll($updateUser);
    if ($res === false) {
      return ['status' => false, 'msg' => '保存失败'];
    }
    return ['status' => true, 'msg' => 'ok'];
  }
}